package com.sias.spring.service;

import com.sias.spring.BeanPostProcessor;
import com.sias.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 吴文杰
 * @version 1.0
 * @createTime 2023-05-28 13:13:19
 */
@Component
public class SiasBeanPostProcessor implements BeanPostProcessor {
  @Override
  public Object postProcessBeforeInitialization(String beanName, Object bean) {
    if (beanName.equals("userService")) {
      System.out.println("postProcessBeforeInitialization");
    }
    return bean;
  }

  @Override
  public Object postProcessAfterInitialization(String beanName, Object bean) {
    if (beanName.equals("userService")) {
      return Proxy.newProxyInstance(SiasBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          System.out.println("代理前逻辑");
          Object invoke = method.invoke(bean, args);
          System.out.println("代理后逻辑");
          return invoke;
        }
      });
    }
    return bean;
  }
}
